// manager/pages/addarea/index.js
import config from '../../../utils/config';
import { request, uploadFile } from '../../../utils/request';
import WxValidate from '../../../common/WxValidate';
Page({

    /**
     * 页面的初始数据
     */
    data: { 
        baseUrl: config.baseUrl,
        addressConfig: config.addressConfig,
        disabled: false,
        latitude: "",
        longitude: "", 
        showPicker: false,
        currentAddress: [{}],
        currentIndex: 0,
        firstLevel: 0,
        addressList: [],
        defaultAddress: [], 
        form: {
            id: "",
            areaName: "",
            areaAbbreviation: "",
            areaPic: "",
            areaCoordinate: "",
            areaAddress: "",
            areaHouseholds: "",
            areaPopulation: "",
            areaContacts: "",
            areaPhone: "",
            remark: "",
        },
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if(options.id){
            this.setData({
                'form.id': options.id
            })
            wx.setNavigationBarTitle({
                title: "编辑网格"
            })
            this.getPersonAreaInfo();
        }else{
            // 获取当前位置
            this.getLatLng();
        }
        if(options.type == "view"){
            wx.setNavigationBarTitle({
                title: "网格详情"
            })
            this.setData({
                disabled: true
            })
        }
        this.initValidate();
        this.getProvinceData();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 输入框输入时
     */
    input(e){
        let key = e.target.dataset.key;
        this.setData({
            ['form.'+key]: e.detail.value
        })     
    },

    /* 地址选择操作方法 */
    openAddress() {
        if(!this.data.disabled){
            this.setData({
                showPicker: true
            })
        }
    },
    // 获取选择的地址
    getAddr(e) {
        let { address, showPicker } = e.detail;
        let { form } = this.data;
        form.areaName = "";
        // let keys = ['proCode', 'cityCode', 'areaCode', 'townCode', 'villagCode'];
        address.forEach((item,index) => {
            form.areaName = form.areaName + item.value.name;
            form[item.key] = item.value.code;
            // form[keys[index]] = item.code;
            // console.log(item.name + "%%%%%" +item.code)
        })
        this.setData({
            form,
            showPicker,
        })
    },
    // 关闭
    closeAddr(e) {
        this.setData({
            showPicker: e.detail.showPicker
        })
    },
    // 获取省级列表
    getProvinceData() {
        let that = this;
        request({
            url: "/commonApi/getAdministrativeDivision",
            method: "GET",
            showLoading: false,
            data: config.addressConfig.proCode?{
                proCode: config.addressConfig.proCode
            }:{
                pLevel: 1
            }
        }).then(res => {
            if(res.code == 0){
                let { defaultAddress } = that.data;
                that.setData({
                    firstLevel: res.data[0].pLevel,
                    addressList: [res.data]
                })
                res.data.forEach(item => {
                    if(defaultAddress[0] == item.code){
                        that.setData({
                            currentAddress: [item]
                        })
                        that.getAreaListByCode(item)
                    }
                })
            }
        })
    },
    // 根据code获取相应的下级菜单
    getAreaListByCode(current) {
        let that =  this;
        let { liveAddress, defaultAddress, currentAddress, currentIndex, addressList } = that.data;
        request({
            url: "/commonApi/getAdministrativeDivision",
            method: "GET",
            showLoading: false,
            data: {
                proCode: current.code
            }
        }).then(res => {
            if(res.code == 0){
                if(!res.data||res.data.length<=0){
                    // let keys = ['proCode', 'cityCode', 'areaCode', 'townCode', 'villagCode'];
                    currentAddress.forEach((item,index) => {
                        liveAddress = liveAddress + item.name;
                    })
                    that.setData({
                        liveAddress
                    })
                    return
                }
                currentIndex = current.pLevel - that.data.firstLevel + 1;
                that.setData({
                    currentIndex: currentIndex,
                    addressList: [...addressList,res.data]
                })
                res.data.forEach(item => {
                    if(defaultAddress[currentIndex] == item.code){
                        that.setData({
                            currentAddress: [...currentAddress,item]
                        })
                        that.getAreaListByCode(item)
                    }
                })
            }
        })
    },

    // 调整定位
    fineLocation(e){
        let that = this;
        wx.chooseLocation({
            latitude: this.data.latitude,
            longitude: this.data.longitude,
            scale: 18,
            success(res){
                console.log(res)
                let latitude = res.latitude;
                let longitude = res.longitude;
                that.getCoordinatePositionInfo(latitude,longitude)
            }
        })
    },
    
    // 获取经纬度
    getLatLng(){
        let that = this;
        wx.getSetting({
            success: (res) => {
                console.log(res)
                if (res.authSetting['scope.userLocation'] == false) {//非初始化进入该页面,且未授权
                    wx.showModal({
                        title: '是否授权当前位置',
                        content: '需要获取您的地理位置，请确认授权',
                        success: function (res) {
                            if (res.confirm) {
                                wx.openSetting({
                                    success: function (data) {
                                        // console.log(data);
                                        if (data.authSetting["scope.userLocation"] == true) {
                                            that.getLocation();
                                        }
                                    }
                                })
                            }
                        }
                    })
                } else {//初始化进入
                    // console.log("KKKKK") 
                    that.getLocation();
                }
            }
        })
    },
    getLocation(){
        const that = this;
        wx.getLocation({
            type: 'gcj02',
            altitude: true,
            isHighAccuracy: true,
            success (res) {
                that.setData({
                    latitude: res.latitude,
                    longitude: res.longitude,
                })
                that.getCoordinatePositionInfo(res.latitude,res.longitude)
            },
            complete: function(res) {
                console.log(res)
                if(res.errMsg == "getLocation:fail auth deny"){
                    // wx.showToast({
                    //     title: '获取定位失败',
                    //     icon: 'none',
                    //     duration: 2000
                    // });
                }
            }
        })
    },
    getCoordinatePositionInfo(latitude,longitude){
        let { form } = this.data;
        request({
            url: "/commonApi/getCoordinatePositionInfo",
            method: "GET",
            data: {
                coordinate: `${latitude},${longitude}`
            }
        }).then(res => {
            if(res.code == 0){
                form.areaCoordinate = `${latitude},${longitude}`;
                form.areaAddress = res.data.address;
                this.setData({
                    form,
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },
    // 网格图片上传
    uploadImage(e) { // 拍摄或从相册选取上传
        let { key, url } = e.detail;
        uploadFile({
            url: "/commonApi/imageUploadAddWatermark",
            filePath: url,
            name: "imgfile",
            formData: {
                coordinate: this.data.form.areaCoordinate,
                watermark: this.data.form.areaAddress,
                fileName: key
            }
        }).then(res => {
            if(res.code == 0){
                this.setData({
                    ['form.'+key]: res.data
                })
            }
        }).catch(error => {
            // console.log(error)
        })
                
    },
    // 保存网格
    save(e) {
        // 传入表单数据，调用验证方法
        if (!this.WxValidate.checkForm(this.data.form)) {
            const error = this.WxValidate.errorList[0]
            this.showModal(error)
            return false
        }
        request({
            url: `/personMarketing/addPersonAreaInfo`,
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: false, // 返回值是否解密
            data: this.data.form
        }).then(res => {
            if(res.code == 0){
                wx.showToast({
                    title: '保存成功',
                    icon: 'none',
                    mask: true,
                    duration: 2000
                });
                setTimeout(()=>{
                    wx.navigateBack()
                },2000)
            }
        }).catch(error => {
            // console.log(error)
        })
    },

    // 网格信息
    getPersonAreaInfo(){
        request({
            url: "/personMarketing/getPersonAreaInfo",
            reqRSAENCRY: true, // 参数是否加密
            resRSADECRY: true, // 返回值是否解密
            data: {
                id: this.data.form.id
            }
        }).then(res => {
            if(res.code == 0){
                let { form } = this.data;
                for(let key in form){
                    form[key] = res.data[key];
                }
                let latitude = res.data.areaCoordinate.split(",")[0];
                let longitude = res.data.areaCoordinate.split(",")[1]; 
                this.setData({
                    form,
                    latitude,
                    longitude
                })
            }
        }).catch(error => {
            // console.log(error)
        })
    },

    // 表单验证
    initValidate() {
        // 验证字段的规则
        const rules = {
            areaName: {
                required: true
            },
            areaAbbreviation: {
                required: true
            },
            // locationPic: {
            //     required: true
            // },
            // areaCoordinate: {
            //     required: true
            // },
            // locationLayers: {
            //     required: true,
            //     digits: true,
            //     min: 1
            // }
        }
        // 验证字段的提示信息，若不传则调用默认的信息
        const messages = {
            areaName: {
                required: '请选择社区/农区网格名称'
            },
            areaAbbreviation: {
                required: '请输入网格简称'
            },
            // locationPic: {
            //     required: '请上传网格照片'
            // },
            // areaCoordinate: {
            //     required: '请获取网格位置'
            // },
            // locationLayers: {
            //     required: '请输入总楼层',
            //     digits: '总楼层为数字',
            //     min: '总楼层不小于1'
            // }
        }
        // 创建实例对象
        this.WxValidate = new WxValidate(rules, messages)
    },
    showModal(error) {
        wx.showToast({
            title: error.msg,
            icon: 'none',
            duration: 2000
        })
    },
})